<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>首页</title>
</head>

<body>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <div>
        <p>聊天窗口:</p>
        <hr>
        <div id="result"></div>
    </div>
    <div>
        <input type="text" placeholder="用户名" id="user">
        <input type="text" placeholder="消息" id="msg">
        <button id="btn">发送</button>
    </div>
    <script>
        $("#btn").on("click", function () {
            let user = $("#user").val()
            let msg = $("#msg").val()
            console.log(user, msg);
            $.ajax({
                url: "http://localhost:3000/message",
                method: 'post',
                data: {
                    user,
                    msg
                },
                success(){
                    // showList()
                }
            })
            
        })

        setInterval(() => {
            showList()
        }, 1000)

        function showList() {
            $("#result").empty()
            $.ajax({
                url: "http://localhost:3000/message",
                method: 'get',
                success(arr) {
                    arr.forEach(obj => {
                        $("#result").append($(`<p>${obj.user} 说: ${obj.msg}</p>`))
                    })
                }
            })

        }
    </script>
</body>

</html>